package com.ben.chatroom.handler;

import com.ben.chatroom.common.cocurrent.FutureTaskScheduler;
import com.ben.chatroom.common.entity.ProtoMsg;
import com.ben.chatroom.processer.ChatRedirectProcessor;
import com.ben.chatroom.session.LocalSession;
import com.ben.chatroom.session.ServerSession;
import com.ben.chatroom.session.SessionManage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author huangyijun
 * 聊天处理器
 */
@Slf4j
@ChannelHandler.Sharable
@Service
public class ChatRedirectHandler extends SimpleChannelInboundHandler<ProtoMsg.Message> {

  private final ChatRedirectProcessor chatRedirectProcessor;

  public ChatRedirectHandler(ChatRedirectProcessor chatRedirectProcessor) {
    this.chatRedirectProcessor = chatRedirectProcessor;
  }

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, ProtoMsg.Message msg) throws Exception {
    if(!chatRedirectProcessor.op().equals(msg.getType())) {
      super.channelRead(ctx, msg);
      return;
    }

    //异步处理转发消息
    FutureTaskScheduler.add(() -> {
      LocalSession localSession = LocalSession.getLocalSession(ctx);
      //如果登录就是用户消息
      if(null != localSession && localSession.isLogin()) {
        chatRedirectProcessor.action(localSession, msg);
        return;
      }

      //没有登录，就是中转消息
      ProtoMsg.MessageRequest request = msg.getMessageRequest();
      List<ServerSession> sessionList = SessionManage.inst().getSessionBy(request.getTo());

      //这是转发过来的信息
      for(ServerSession serverSession : sessionList) {
        if(serverSession instanceof LocalSession) {
          serverSession.writeAndFlush(msg);
        }
      }

    });


  }

  @Override
  public void channelInactive(ChannelHandlerContext ctx) {
    LocalSession session = ctx.channel().attr(LocalSession.SESSION_KEY).get();
    if(null != session && session.isValid()) {
      session.close();
      SessionManage.inst().removeSession(session.getSessionId());
    }
  }
}
